
import re
import sys
from TableOne import Tableone

class Textone():
    def __init__(self,**params1):
        self.config = params1['config']
        self.get_money = params1['get_money']
        self.params1 = params1
    def get_winner_company_name(self, value):
        if value[1] == "为":
            value = value[1:]
        if value[-1] == "为":
            value = value[0:-1]
        return value

    def get_fir(self,result_end_data):
        not_fir = []
        fir = []
        slow = []
        for i in result_end_data:
            if '_fir' not in i['第一中标候选人'] and '_slow' not in i['第一中标候选人'] :
                not_fir.append(i)
            elif '_slow' in i['第一中标候选人']:
                slow.append(i)
            else:
                fir.append(i)

        if fir != []:
            for i in fir:
                i['第一中标候选人'] = i['第一中标候选人'].split('_fir')[1]
            return fir
        elif not_fir != []:
            return not_fir
        else:

            for i in slow:
                i['第一中标候选人'] = i['第一中标候选人'].split('_slow')[1]
            return slow
    def biao(self,result_end_data):
        for i in result_end_data:
            i['which_part'] = 'One'
        return result_end_data
    def ge(self,number_one_data):
        out = {}
        out['第一中标候选人'] = []
        out['第二中标候选人'] = []
        out['第三中标候选人'] = []
        for i in number_one_data:
            out['第一中标候选人'].append({'公司名称':i['第一中标候选人'],'中标金额':i['中标金额'],'项目负责人':i['项目负责人'],'项目负责人资格':i['项目负责人资格'],'项目负责人证书编号':i['项目负责人证书编号'],'项目负责人_资格_编号':i['项目负责人_资格_编号'],'标段':i['标段']})
            del i['中标金额'],i['项目负责人'],i['项目负责人资格'],i['项目负责人证书编号'],i['项目负责人_资格_编号'],i['标段']
        return out

    def part_one_text(self,html):
        r = {}
        for i in self.config['find_key_one']:
            obj = re.finditer(i["value"],html,re.I | re.S)
            for x in obj:
                if "中标金额x" in i["key"]:
                    r[x.start()] = {"key": "中标金额x", "value": re.sub(self.config['company_chose'][0], "", x.group(), flags=re.S | re.I)}
                else:
                    r[x.start()] = {"key": i["key"], "value": x.group()}
        end_data = []
        end_list = {}
        winner_index = 0
        tender = ""
        rx = sorted(r.items(), key=lambda d:d[0], reverse=False)
        money_maybe = ''
        for i in range(0, len(rx)):
            v = rx[i][1]
            vkey = v["key"]
            vreg = v["value"]
            if vkey == self.config['keyword_one'][0]:
                valid_obj = re.search(self.config['company_chose'][0], vreg, re.S | re.I)
                if valid_obj:
                    if self.config['keyword_one'][0] not in end_list:
                        end_list[self.config['keyword_one'][0]] = vreg
                    else:
                        if '中标金额' not in end_list and money_maybe != '':
                            end_list['中标金额'] = money_maybe
                            money_maybe = ''
                        end_data.append(end_list)
                        end_list = {}
                        end_list[self.config['keyword_one'][0]] = vreg
                    winner_index = rx[i][0]
                    tender_obj = re.match(self.config['find_tender_form_company'], vreg, re.I | re.S)
                    if tender_obj:
                        end_list[self.config['keyword_one'][0]] = re.sub(re.escape(tender_obj.group()), "", end_list[self.config['keyword_one'][0]], flags=re.I | re.S)
                    else:
                        if tender != "":
                            if (winner_index - rx[i][0]) > -200 and (winner_index - rx[i][0]) < 200:
                                end_list[self.config['keyword_one'][3]] = tender
                                tender = ""
            elif vkey == self.config['keyword_one'][1]:

                if re.search('[元万%率零壹贰貳叁肆伍陆柒捌玖拾佰仟萬亿圆元万整\d]',vreg) == None:
                    continue
                if vreg[0] in ['是','为']:
                    vreg = vreg[1:]
                if re.search('[购买]',vreg):
                    vreg = re.split('[购买]',vreg)[0]
                new_index = html.index(vreg) + len(vreg)
                if new_index < len(html):
                    if html[new_index] in ['%', '元']:
                        vreg += html[html.index(vreg) + len(vreg)]
                vreg = re.sub('第一中标候选人|[（）]|下浮|K＝', '', vreg)
                if re.search('预算价',vreg):
                    continue

                if self.config['keyword_one'][0] in end_list:
                    if self.config['keyword_one'][1] not in end_list:
                        if self.config['keyword_one'][4] in end_list:
                            del end_list[self.config['keyword_one'][4]]
                        end_list[self.config['keyword_one'][1]] = vreg
                else:
                    money_maybe = vreg

            elif vkey == self.config['keyword_one'][2]:
                if self.config['keyword_one'][0] in end_list:
                    if self.config['keyword_one'][2] not in end_list:
                        vreg = re.sub('第一中标候选人|[（）]|项目负责人','',vreg)
                        end_list[self.config['keyword_one'][2]] = vreg

            elif vkey == self.config['keyword_one'][3]:
                tender = vreg
                if self.config['keyword_one'][0] in end_list:
                    if self.config['keyword_one'][3] not in end_list:
                        if (winner_index - rx[i][0]) > -200 and (winner_index - rx[i][0]) < 200:
                            end_list[self.config['keyword_one'][3]] = tender
                            tender = ""

            elif vkey == self.config['keyword_one'][4]:
                if self.config['keyword_one'][0] in end_list:
                    if self.config['keyword_one'][1] not in end_list:
                        if self.config['keyword_one'][4] not in end_list:
                            if (winner_index - rx[i][0]) > -100 and (winner_index - rx[i][0]) < 100:
                                if html[html.index(vreg) + len(vreg)] in ['%', '元']:
                                    vreg += html[html.index(vreg) + len(vreg)]
                                vreg = re.sub('第一中标候选人|[（）]|K＝','',vreg)
                                if len(vreg) != 17:
                                    end_list[self.config['keyword_one'][4]] = vreg

        if end_list != {}:
            if '中标金额' not in end_list and money_maybe != '':
                end_list['中标金额'] = money_maybe
                money_maybe = ''
            end_data.append(end_list)

        for _ in end_data:
            if '第一中标候选人' in _:
                if '_fir:' in _['第一中标候选人']:
                    _['第一中标候选人'] = _['第一中标候选人'].replace('_fir:','_fir')

        end_data = self.get_fir(end_data)
        result_end_data = []
        for i in end_data:
            v = i[self.config['keyword_one'][0]]
            m = "0"
            t = ""
            c = ""

            if self.config['keyword_one'][1] in i:
                if i[self.config['keyword_one'][1]] != '':
                    if i[self.config['keyword_one'][1]][0] in [':']:
                        i[self.config['keyword_one'][1]] = i[self.config['keyword_one'][1]][1:]
                try:
                    m = self.get_money(i[self.config['keyword_one'][1]])
                except:
                    m = i[self.config['keyword_one'][1]]
            else:
                if self.config['keyword_one'][4] in i:
                    if i[self.config['keyword_one'][4]] != '':
                        if i[self.config['keyword_one'][4]][0] in [':']:
                            i[self.config['keyword_one'][4]] = i[self.config['keyword_one'][4]][1:]
                    m = self.get_money(i[self.config['keyword_one'][4]])

            if self.config['keyword_one'][3] in i:
                t = re.sub("[:◄]", "", i[self.config['keyword_one'][3]], flags=re.S | re.I)

            if self.config['keyword_one'][2] in i:
                c = re.sub("[:◄]", "", i[self.config['keyword_one'][2]], flags=re.S | re.I)

            v = re.sub("(（?(牵头人|成员|联合体)）?|;|◄|、|(设计|施工|监理|勘察)方：?|/|&)", ":", v, flags=re.S | re.I)
            line = re.split(":", v)
            for k in line:
                if (k != "") and (len(k) >= 5):
                    w = self.get_winner_company_name(k)
                    result_end_data.append({self.config['keyword_one'][0]: w, self.config['keyword_one'][3]: t, self.config['keyword_one'][1]: m, self.config['keyword_one'][2]: c})
        result_end_data = self.company_concat(result_end_data)
        result_end_data = self.biao(result_end_data)
        result_end_data = self.supply(result_end_data)
        result_end_data = Tableone(**self.params1).handle_mp(result_end_data)
        result_end_data = self.end_data_clear(result_end_data)
        result_end_data = self.ge(result_end_data)
        return result_end_data

    def company_concat(self,result_end_data):

        company_dict = {}
        out_result = []
        for i in result_end_data:
            key = re.sub('_(fir|slow)','',i['第一中标候选人'])
            company_dict[key] = company_dict.get(key,[]) + [i]
        for i in company_dict:
            if i != '':
                biao_dict = {}
                for j in company_dict[i]:
                    key = j['标段']
                    biao_dict[key] = biao_dict.get(key,[]) + [j]
                for j in biao_dict:
                    biao_out = {'第一中标候选人': '', '标段': '', '中标金额': '0', '项目负责人': ''}
                    for m in biao_dict[j]:
                        if '_fir' in m['第一中标候选人']:
                            biao_out['第一中标候选人'] = m['第一中标候选人'].replace('_fir','')
                        elif '_slow' in m['第一中标候选人'] and biao_out['第一中标候选人'] == '':
                            biao_out['第一中标候选人'] = m['第一中标候选人'].replace('_slow','')
                        elif '_fir' not in biao_out['第一中标候选人']:
                            biao_out['第一中标候选人'] = m['第一中标候选人']
                        for n in ['标段','中标金额','项目负责人']:
                            if biao_out[n] in ['','0']:
                                biao_out[n] = m[n]
                    out_result.append(biao_out)
        return out_result


    def end_data_clear(self,result_end_data):
        for i in result_end_data:
            for j in i:
                if isinstance(i[j],str):
                    i[j] = re.sub('\xa0','',i[j])
        return result_end_data
    def supply(self, number_one_data):
        for i in number_one_data:
            i['which_part'] = 'Two'
            for j in ['第一中标候选人', '中标金额', '项目负责人', '标段','项目负责人资格','项目负责人证书编号','项目负责人_资格_编号']:
                if j in i:
                    continue
                else:
                    i[j] = ''
        return number_one_data

if __name__ == '__main__':
    html = open("C:/Users/Administrator/Desktop/table_easy/table30.html", encoding="utf-8").read()
    print(Text().part_one(html))